/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.mapper.UserMapper;
import me.zhengjie.modules.system.mapper.UserRoleMapper;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.system.service.StudentService;
import me.zhengjie.modules.system.domain.vo.StudentQueryCriteria;
import me.zhengjie.modules.system.mapper.StudentMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import me.zhengjie.utils.PageResult;

import static me.zhengjie.modules.system.service.impl.TeacherServiceImpl.validateEmail;
import static me.zhengjie.modules.system.service.impl.TeacherServiceImpl.validatePhoneNumber;

/**
* @description 服务实现
* @author tianjiaqi
* @date 2024-04-06
**/
@Service
@RequiredArgsConstructor
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    private final StudentMapper studentMapper;

    private final UserMapper userMapper;

    private final PasswordEncoder passwordEncoder;

    private final UserRoleMapper userRoleMapper;

    private final UserService userService;
    @Override
    public PageResult<Student> queryAll(StudentQueryCriteria criteria, Page<Object> page){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
        criteria.setSchoolId(currentUser.getDeptId());


     
        PageResult<Student> teacherResults =  PageUtil.toPage(studentMapper.findAll(criteria, page));

        List<Long> ids = new ArrayList<>();
        teacherResults.getContent().forEach(teach -> {
            if(teach.getUserid()!=null){
                ids.add(teach.getUserid());
            }

        });
        List<User> userList = new ArrayList<>();

        if(!ids.isEmpty()){
            userList = userMapper.selectBatchIds(ids);
        }

        List<User> finalUserList = userList;
        teacherResults.getContent().forEach(teachItem -> {
            finalUserList.forEach(user -> {
                if(teachItem.getUserid() == user.getId()){
                    teachItem.setUsername(user.getUsername());
                    teachItem.setNickName(user.getNickName());
                    teachItem.setAvatarName(user.getAvatarName());
                    teachItem.setPhone(user.getPhone());
                    teachItem.setEmail(user.getEmail());
                    teachItem.setGender(user.getGender());
                    teachItem.setEnabled(user.getEnabled());
                    teachItem.setCreatetime(String.valueOf(user.getCreateTime()));
                }
            });
        });

        return teacherResults;
    }

    @Override
    public List<Student> queryAll(StudentQueryCriteria criteria){
        return studentMapper.findAll(criteria);
    }

    public Map<String,Object> checkStudent(Student resources) {
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        String currentUserName = authentication.getName();
//        User currentUser = userMapper.findByUsername(currentUserName);
//
//        resources.setSchoolid(currentUser.getDeptId());
        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("username",resources.getUsername());
        User currentUser2 = userMapper.selectOne(queryWrapper1);

        Map<String,Object> map = new HashMap<>();
        map.put("number",resources.getNumber());
        map.put("numberType",null);

        map.put("name",resources.getUsername());
        map.put("nameType",null);

        if(resources.getUsername() == null){
            map.put("nameType","登录名不能为空");
        }

        map.put("username",resources.getUsername());
        map.put("usernameType",null);

        if(resources.getUsername() == null){
            map.put("nameType","登录名不能为空");
        }

        map.put("nickName",resources.getNickName());

        if(resources.getNickName() == null){
            map.put("nickNameType","姓名不能为空");
        }

        map.put("email",resources.getEmail());
        map.put("emailType",null);

        map.put("phone",resources.getPhone());
        map.put("phoneType",null);

        map.put("gender",resources.getGender());
        map.put("genderType",null);

        map.put("avatarPath",resources.getAvatarPath());
        map.put("password",resources.getPassword());
        map.put("status",0);

        if(!String.valueOf(resources.getGender()).equals("男") && !String.valueOf(resources.getGender()).equals("女")){
            map.put("genderType","性别信息智能为男或女");
        }

        if(currentUser2!=null){

            map.put("usernameType","用户名重复");
            map.put("status",1);
        }

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email",resources.getEmail());
        User repeatEmailUser =  userMapper.selectOne(queryWrapper);
        if(repeatEmailUser!= null && repeatEmailUser.getId() != resources.getUserid()){

            map.put("emailType","邮箱重复");
            map.put("status",1);
        }

        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("phone",resources.getPhone());
        User repeatPhoneUser =  userMapper.selectOne(queryWrapper2);
        if(repeatPhoneUser!= null && repeatPhoneUser.getId() != resources.getUserid()){
//            return -4;
            map.put("phoneType","手机号重复");
            map.put("status",1);
        }
        if(resources.getEmail() != null){
            if(!validateEmail(resources.getEmail())){
                map.put("emailType","邮箱格式错误");
                map.put("status",1);
            }
        } else {
            map.put("emailType","邮箱格式为空");
            map.put("status",1);
        }


        if(resources.getPhone() != null){
            if(!validatePhoneNumber(resources.getPhone())){
                map.put("phoneType","手机号格式错误");
                map.put("status",1);
            }
        } else {
            map.put("phoneType","手机号不能为空");
            map.put("status",1);
        }

        QueryWrapper queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("number",resources.getNumber());
        Student repeatStudentUser =  studentMapper.selectOne(queryWrapper3);
        if(repeatStudentUser!= null && resources.getId()!=repeatStudentUser.getId()){

            map.put("numberType","学号重复");
            map.put("status",1);
        }

        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer create(Student resources) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
        resources.setSchoolid(currentUser.getDeptId());

        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("username",resources.getUsername());
        User currentUser2 = userMapper.selectOne(queryWrapper1);
        if(currentUser2!=null){
            return -3;
        }

        User user = new User();
        user.setUsername(resources.getUsername());
        user.setNickName(resources.getNickName());
        user.setDeptId(currentUser.getDeptId());
        user.setPassword(passwordEncoder.encode(resources.getPassword()));
        user.setType(2);
        user.setGender(resources.getGender());

        user.setEmail(resources.getEmail());
        user.setPhone(resources.getPhone());
        user.setEnabled(resources.getEnabled());

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email",resources.getEmail());
        User repeatEmailUser =  userMapper.selectOne(queryWrapper);
        if(repeatEmailUser!= null){
            return -1;
        }
        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("phone",resources.getPhone());
        User repeatPhoneUser =  userMapper.selectOne(queryWrapper2);
        if(repeatPhoneUser!= null){
            return -4;
        }

        QueryWrapper queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("number",resources.getNumber());
        Student repeatStudentUser =  studentMapper.selectOne(queryWrapper3);
        if(repeatStudentUser!= null){
            return -5;
        }

        Set<Job> jobs = new HashSet<>();
        Job job = new Job();
        job.setId(11L);
        jobs.add(job);
        user.setJobs(jobs);

        Set<Role> roles = new HashSet<>();
        Role role = new Role();
        role.setId(4L);
        roles.add(role);
        user.setRoles(roles);

        Dept dept = new Dept();
        dept.setId(currentUser.getDeptId());
        user.setDept(dept);

        userService.create(user);

        resources.setUserid(user.getId());
        resources.setName(resources.getUsername());
        save(resources);
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer update(Student resources) throws Exception {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
        resources.setSchoolid(currentUser.getDeptId());

        User currentUser2 = userMapper.findByUsername(resources.getUsername());
        System.out.println("==currentUser2=="+currentUser2);
        System.out.println("==currentUser1=="+currentUser2.getId());
        System.out.println("==currentUser3=="+resources.getUserid());
        if(currentUser2 !=null && Math.toIntExact(currentUser2.getId()) != resources.getUserid()){
            return -3;
        }

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email",resources.getEmail());
        User repeatEmailUser =  userMapper.selectOne(queryWrapper);
        if(repeatEmailUser!= null && Math.toIntExact(repeatEmailUser.getId()) != resources.getUserid()){
            return -1;
        }
        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("phone",resources.getPhone());
        User repeatPhoneUser =  userMapper.selectOne(queryWrapper2);
        if(repeatPhoneUser!= null && Math.toIntExact(repeatPhoneUser.getId()) != resources.getUserid()){
            return -4;
        }

        QueryWrapper queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("number",resources.getNumber());
        Student repeatStudentUser =  studentMapper.selectOne(queryWrapper2);
        if(repeatStudentUser!= null && Math.toIntExact(repeatStudentUser.getId()) != resources.getId()){
            return -5;
        }


//        User user = new User();
//        user.setId(resources.getId());


        QueryWrapper queryWrapper5 = new QueryWrapper<>();
        queryWrapper5.eq("user_id",resources.getUserid());
        User user = userMapper.selectOne(queryWrapper5);
        user.setUsername(resources.getUsername());
        user.setNickName(resources.getNickName());
        user.setDeptId(currentUser.getDeptId());
        user.setPassword(passwordEncoder.encode(currentUser.getPassword()));
        user.setAvatarName(resources.getAvatarName());
        user.setAvatarPath(resources.getAvatarPath());
        user.setGender(resources.getGender());

        user.setEmail(resources.getEmail());
        user.setPhone(resources.getPhone());
        user.setEnabled(resources.getEnabled());

        Set<Job> jobs = new HashSet<>();
        Job job = new Job();
        job.setId(11L);
        jobs.add(job);
        user.setJobs(jobs);

        Set<Role> roles = new HashSet<>();
        Role role = new Role();
        role.setId(5L);
        roles.add(role);
        user.setRoles(roles);

        Dept dept = new Dept();
        dept.setId(currentUser.getDeptId());
        user.setDept(dept);
//        userService.create(user);
//        userService.update(user);
        user.setPassword(passwordEncoder.encode(resources.getPassword()));
//        QueryWrapper queryWrapper1 = new QueryWrapper<User>();
//        queryWrapper1.eq("user_id",resources.getId());
        userService.update(user);
        resources.setUserid(user.getId());

        Student student = getById(resources.getId());
        student.copy(resources);
        saveOrUpdate(student);

        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {
        List<Student> list = studentMapper.selectBatchIds(ids);
        List<Integer> studentIds = new ArrayList<>();
        for(Student student : list){
            studentIds.add(Math.toIntExact(student.getUserid()));
        }
        userMapper.deleteBatchIds(studentIds);
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<Student> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Student student : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("学号", student.getNumber());
            map.put(" userid",  student.getUserid());
            map.put(" lastupdatetime",  student.getLastupdatetime());
            map.put("名称", student.getName());
            map.put(" createtime",  student.getCreatetime());
            map.put("组织id", student.getSchoolid());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}